const models = require('./../db/mysqldb/index')
const {
  ErrorModel,
  encrypt,
  SuccessModel,
  validate
} = require('./../utils/index')
const { saltTime } = require('./../config/index')
const logger = require('./../utils/logger')
const svgCaptcha = require('svg-captcha')
const jwt = require('jsonwebtoken')
const config = require('./../config/index')

class SysUserController {
  /**
   * @description 获取验证码
   * @param {*} req
   * @param {*} res
   */
  static async getCode(req, res) {
    const codeConfig = {
      size: 2,
      ignoreChars: '0o1i',
      noise: 1,
      color: true,
      // 宽度
      width: 130,
      // 高度
      height: 40,
      background: '#cc9966'
    }
    let captcha = svgCaptcha.createMathExpr(codeConfig)
    req.session.captcha = captcha.text.toLocaleLowerCase()
    res.json(new SuccessModel({ data: captcha.data }))
  }
  /**
   * @description 登陆
   * @param {*} username
   * @param {*} password
   * @param {*} captcha
   */
  static async login(req, res, next) {
    const { username, password, captcha } = req.body
    logger.info(`SysUserController`, 'login', `req.body`, req.body)
    if (!captcha) {
      res.json(new ErrorModel([], `请输入验证码`))
      return
    }
    if (!username || !password) {
      res.json(new ErrorModel([], `请输入用户名或密码`))
      return
    }
    try {
      const sessionCaptcha = req.session.captcha
      if (sessionCaptcha !== captcha) {
        res.json(new ErrorModel([], `验证码错误`))
        return
      }
      const user = await models.sys_user.findOne({
        where: {
          username
        }
      })
      logger.info(`SysUserController`, 'login', `user`, user)
      if (!user) {
        res.json(new ErrorModel([], `用户不存在`))
        return
      }
      const opassword = await validate(password, user.password)
      if (!opassword) {
        res.json(new ErrorModel([], `密码错误`))
        return
      }
      if (user.del_flag == '1') {
        res.json(new ErrorModel([], `禁止登录，请联系管理员！`))
        return
      }
      console.log(user.user_id)
      const userRole = await models.sys_role_user.findOne({
        where: {
          user_id: user.user_id
        }
      })
      logger.info(`SysUserController`, 'login', `userRole`, userRole)
      let roleInfo = {}
      if (userRole.role_id) {
        roleInfo = await models.sys_role.findOne({
          where: {
            role_id: userRole.role_id
          }
        })
      }
      logger.info(`SysUserController`, 'login', `roleInfo`, roleInfo)
      let datas = {
        user_id: user.user_id,
        username,
        role_id: userRole ? userRole.role_id : '',
        role_code: roleInfo ? roleInfo.role_code : '',
        dept_id: user.dept_id
      }
      logger.info(datas)
      jwt.sign(
        datas,
        config.secretOrKey,
        // 设置过期时间
        { expiresIn: 60 * 60 * 24 },
        (err, token) => {
          if (err) {
            logger.info(`SysUserController`, 'login', `jwt-err`, err)
            res.json(new ErrorModel([], err.message))
          } else {
            logger.info(`SysUserController`, 'login', `jwt-token`, token)
            res.json(
              new SuccessModel(
                { token: 'Bearer ' + token, isLogin: true },
                '登录成功'
              )
            )
          }
        }
      )
    } catch (error) {
      logger.error(`SysUserController`, 'login', `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 添加用户
   * @param {*} username
   * @param {*} dept_id
   * @param {*} realname
   * @param {*} phone
   */
  static async userAdd(req, res, next) {
    const { username, dept_id, realname, phone } = req.body
    logger.info(`SysUserController`, `userAdd`, `req.body`, req.body)
    if (!username || !dept_id) {
      res.json(new ErrorModel([], `请输入用户名或密码`))
      return
    }
    try {
      const npassword = await encrypt(config.defaultpassword, saltTime)
      logger.info(`SysUserController`, `userAdd`, `npassword`, npassword)
      const result = await models.sys_user.create({
        username,
        password: npassword,
        dept_id,
        realname,
        phone
      })
      logger.info(`SysUserController`, `userAdd`, `result`, result)
      res.json(new SuccessModel([], `新增用户成功`))
    } catch (error) {
      logger.error(`SysUserController`, `userAdd`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 添加用户
   * @param {*} user_id
   * @param {*} dept_id
   * @param {*} username
   * @param {*} realname
   * @param {*} phone
   */
  static async userUpd(req, res, next) {
    const { user_id, username, dept_id, realname, phone } = req.body
    logger.info(`SysUserController`, `userUpd`, `req.body`, req.body)
    if (!user_id || !dept_id) {
      res.json(new ErrorModel([], `请输入必填项`))
      return
    }
    try {
      const result = await models.sys_user.update(
        {
          username,
          dept_id,
          realname,
          phone
        },
        {
          where: { user_id }
        }
      )
      logger.info(`SysUserController`, `userUpd`, `result`, result)
      res.json(new SuccessModel([], `用户更新成功`))
    } catch (error) {
      logger.error(`SysUserController`, `userUpd`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 删除用户
   * @param {*} user_id
   */
  static async userDel(req, res, next) {
    const { user_id } = req.body
    logger.info(`SysUserController`, `userDel`, `req.body`, req.body)
    if (!user_id) {
      res.json(new ErrorModel([], `user_id 获取失败`))
      return
    }
    try {
      const result = await models.sys_user.update(
        {
          del_flag: '1'
        },
        {
          where: { user_id }
        }
      )
      logger.info(`SysUserController`, `userDel`, `result`, result)
      res.json(new SuccessModel([], `删除用户成功`))
    } catch (error) {
      logger.error(`SysUserController`, `userDel`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 用户与角色绑定
   * @param {*} req
   * @param {*} res
   * @param {*} next
   */
  static async roleUser(req, res, next) {
    const { role_id, user_id } = req.body
    logger.info(`SysUserController`, `roleUser`, `req.body`, req.body)
    try {
      const has_user_id = await models.sys_role_user.findOne({
        where: {
          user_id
        }
      })
      logger.info(`SysUserController`, `roleUser`, `has_user_id`, has_user_id)
      if (has_user_id) {
        const updateRoleUser = await models.sys_role_user.update(
          {
            role_id
          },
          {
            where: {
              user_id
            }
          }
        )
        logger.info(
          `SysUserController`,
          `roleUser`,
          `updateRoleUser`,
          updateRoleUser
        )
      } else {
        const insertRoleUser = await models.sys_role_user.create({
          role_id,
          user_id
        })
        logger.info(
          `SysUserController`,
          `roleUser`,
          `insertRoleUser`,
          insertRoleUser
        )
      }
      res.json(new SuccessModel([], `更新成功`))
    } catch (error) {
      res.json(new ErrorModel([], error.message))
      return
    }
  }
  /**
   * @description 修改密码
   * @param {*} password
   * @param {*} newPassword
   */
  static async modifypwd(req, res, next) {
    const { password, newPassword } = req.body
    const { user_id } = req.user
    logger.info('modifypwd', `req.body`, req.body)
    if (!password) {
      res.json(new ErrorModel([], `请输入密码`))
      return
    }
    try {
      const vf = await validate(password, newPassword)
      logger.info('modifypwd', `vf`, vf)
      if (vf) {
        const npassword = await encrypt(newPassword, saltTime)
        logger.info('modifypwd', `npassword`, npassword)
        const updateInfo = await models.sys_user.update(
          {
            password: npassword
          },
          {
            where: {
              user_id
            }
          }
        )
        logger.info('modifypwd', `updateInfo`, updateInfo)
      }
      res.json(new SuccessModel([], `更新成功`))
    } catch (error) {
      res.json(new ErrorModel([], error.message))
      return
    }
  }
  /**
   * 根据部门获取用户信息
   */
  static async userByDept(req,res,next){
    const {dept_id} = req.body
    logger.info(`SysUserController`, 'userByDept', `req.body`, req.body)
    if (!dept_id) {
      res.json(new ErrorModel([], `缺少必填项`))
      return
    }
    try {
      const userInfo = await models.sys_user.findAll({
        where:{
          dept_id
        }
      })
      logger.info(`SysUserController`, 'userByDept', `userInfo`, userInfo)
      res.json(new SuccessModel(userInfo))
    } catch (error) {
      res.json(new ErrorModel([], error.message))
      logger.error(`SysUserController`, 'userByDept', `error`, error)
      return
    }
  }
}

module.exports = {
  SysUserController
}
